package cn.tannn.tgateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 抽象的 plugin 处理一些公共的事件 （中间层
 *
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @date 2024/5/30 下午3:56
 */
@Slf4j
public abstract class AbstractGatewayPlugin implements GatewayPlugin {

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public boolean support(ServerWebExchange exchange) {
        return doSupport(exchange);

    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, GatewayPluginChain chain) {
        boolean supported = doSupport(exchange);
        log.debug(" =====>>>> plugin[{}], support= {}", this.getName(), supported);
        // 支持就走 handle， 不支持则继续执行chain逻辑，不打断 plugin链
        return supported ? doHandle(exchange, chain) : chain.handle(exchange);
    }

    /**
     * 是否支持当前 server web Internal 的处理，避免 plugin 处理了不该自己处理的请求
     *
     * @param exchange {@link ServerWebExchange}
     * @return false 不支持
     */
    public abstract boolean doSupport(ServerWebExchange exchange);

    /**
     * 具体的处理
     *
     * @param exchange {@link ServerWebExchange}
     * @return {@link Mono}
     */
    public abstract Mono<Void> doHandle(ServerWebExchange exchange, GatewayPluginChain chain);
}
